<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use EasyWeChat\Factory;
use think\facade\Cache;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
		$this->checkToken();
    }
	
	// 验证token
	protected function checkToken()
	{
		$redis = Cache::store('redis');
		$header = $this->request->header();
			
		$pathinfo = $this->request->pathinfo();
		$bool = true;
		if($pathinfo == 'index/login') $bool = false; // pc登录
		if($pathinfo == 'index/codeQrList') $bool = false; // 
		if($pathinfo == 'base/baseAdd') $bool = false; // 
		
		if($bool){
			if(isset($header['authorization'])){
			  $token = $this->request->header()['authorization'];
			  $arr = explode('_',$token);
			  $cid = $redis->get($arr[0]);
			  $webcid = $arr[1];
			  if($cid!=$webcid){
				$this->returnJson(401,'请登录',[]);
				die();
			   }
			}else{
			   $this->returnJson(401,'请登录',[]);
			   die();
			}
		}
			
			
			
			
			
			
	}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    //返回json格式消息
    public function returnJson($code, $msg, $data=[])
    {
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        $arr['data'] = $data;
        echo json_encode($arr);
    }
	
	// 随机生成num个不同的数字
	public function create_rand_num($num)
	{
		//定义一个包含0-9的数组
		$arr = [0,1,2,3,4,5,6,7,8,9];
		// //随机生成4个不同的数字
		$newArr = [];
		while(count($newArr) < $num){
			$key = array_rand($arr);
			if(!in_array($arr[$key],$newArr)){
				$newArr[] = $arr[$key];
			}
		}
		
		//将这四个数字组成一个字符串
		$code = implode('',$newArr);
		return $code;
		
	}

    /**
     * 获取小程序实例
     * @return \EasyWeChat\MiniProgram\Application
     */
    public static function getEasyWeChatMiniProgram()
    {
        return Factory::miniProgram(config('wechat.mini_program'));
    }
	
	/**
	 * 获取公众号实例
	 * @return \EasyWeChat\OfficialAccount\Application
	 */
	public static function  getEasyWeChatOfficialAccount()
	{
		$config = [
		    'app_id' => 'wx311fcb7191d9cb5d',
		    'secret' => '05987d4d516cdff41143b7deba1a18e7',
		
		    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
		    'response_type' => 'array',
		    
		    //...
		];
		return Factory::officialAccount($config);
	}
	
    // 数组去重
    public static function array_unique_key($arr,$key){
        $tmp_arr = array();
        foreach($arr as $k => $v){
            if(in_array($v[$key],$tmp_arr)){
                unset($arr[$k]);
            }else{
                $tmp_arr[]=$v[$key];
            }
        }
        return $tmp_arr;
    }
	// 二维数组去重返回二维数组
	public static function array_unique($arr,$key){
	    $tmp_arr = array();
	    foreach($arr as $k => $v){
	        if(in_array($v[$key],$tmp_arr)){
	            unset($arr[$k]);
	        }else{
	            $tmp_arr[]=$v[$key];
	        }
	    }
	    return $arr;
	}
}
